home *** CD-ROM | disk | FTP | other *** search
/ Chip 2006 June / CHIP 2006-06.2.iso / program / freeware / Democracy-0.8.2.exe / xulrunner / python / BitTorrent / bencode.py < prev    next >
Encoding:
Python Source  |  2006-04-10  |  3.3 KB  |  131 lines

  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.0 (the License).  You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License.  You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10.  
  11. # Written by Petru Paler
  12.  
  13. from BitTorrent.obsoletepythonsupport import *
  14.  
  15. from BitTorrent import BTFailure
  16.  
  17. def decode_int(x, f):
  18.     f += 1
  19.     newf = x.index('e', f)
  20.     n = int(x[f:newf])
  21.     if x[f] == '-':
  22.         if x[f + 1] == '0':
  23.             raise ValueError
  24.     elif x[f] == '0' and newf != f+1:
  25.         raise ValueError
  26.     return (n, newf+1)
  27.  
  28. def decode_string(x, f):
  29.     colon = x.index(':', f)
  30.     n = int(x[f:colon])
  31.     if x[f] == '0' and colon != f+1:
  32.         raise ValueError
  33.     colon += 1
  34.     return (x[colon:colon+n], colon+n)
  35.  
  36. def decode_list(x, f):
  37.     r, f = [], f+1
  38.     while x[f] != 'e':
  39.         v, f = decode_func[x[f]](x, f)
  40.         r.append(v)
  41.     return (r, f + 1)
  42.  
  43. def decode_dict(x, f):
  44.     r, f = {}, f+1
  45.     lastkey = None
  46.     while x[f] != 'e':
  47.         k, f = decode_string(x, f)
  48.         if lastkey >= k:
  49.             raise ValueError
  50.         lastkey = k
  51.         r[k], f = decode_func[x[f]](x, f)
  52.     return (r, f + 1)
  53.  
  54. decode_func = {}
  55. decode_func['l'] = decode_list
  56. decode_func['d'] = decode_dict
  57. decode_func['i'] = decode_int
  58. decode_func['0'] = decode_string
  59. decode_func['1'] = decode_string
  60. decode_func['2'] = decode_string
  61. decode_func['3'] = decode_string
  62. decode_func['4'] = decode_string
  63. decode_func['5'] = decode_string
  64. decode_func['6'] = decode_string
  65. decode_func['7'] = decode_string
  66. decode_func['8'] = decode_string
  67. decode_func['9'] = decode_string
  68.  
  69. def bdecode(x):
  70.     try:
  71.         r, l = decode_func[x[0]](x, 0)
  72.     except (IndexError, KeyError, ValueError):
  73.         raise BTFailure, 'not a valid bencoded string'
  74.     if l != len(x):
  75.         raise BTFailure, 'invalid bencoded value (data after valid prefix)'
  76.     return r
  77.  
  78. from types import StringType, IntType, LongType, DictType, ListType, TupleType
  79.  
  80.  
  81. class Bencached(object):
  82.  
  83.     __slots__ = ['bencoded']
  84.  
  85.     def __init__(self, s):
  86.         self.bencoded = s
  87.  
  88. def encode_bencached(x,r):
  89.     r.append(x.bencoded)
  90.  
  91. def encode_int(x, r):
  92.     r.extend(('i', str(x), 'e'))
  93.  
  94. def encode_string(x, r):
  95.     r.extend((str(len(x)), ':', x))
  96.  
  97. def encode_list(x, r):
  98.     r.append('l')
  99.     for i in x:
  100.         encode_func[type(i)](i, r)
  101.     r.append('e')
  102.  
  103. def encode_dict(x,r):
  104.     r.append('d')
  105.     ilist = x.items()
  106.     ilist.sort()
  107.     for k, v in ilist:
  108.         r.extend((str(len(k)), ':', k))
  109.         encode_func[type(v)](v, r)
  110.     r.append('e')
  111.  
  112. encode_func = {}
  113. encode_func[Bencached] = encode_bencached
  114. encode_func[IntType] = encode_int
  115. encode_func[LongType] = encode_int
  116. encode_func[StringType] = encode_string
  117. encode_func[ListType] = encode_list
  118. encode_func[TupleType] = encode_list
  119. encode_func[DictType] = encode_dict
  120.  
  121. try:
  122.     from types import BooleanType
  123.     encode_func[BooleanType] = encode_int
  124. except ImportError:
  125.     pass
  126.  
  127. def bencode(x):
  128.     r = []
  129.     encode_func[type(x)](x, r)
  130.     return ''.join(r)
  131.